<?php
/*
 +----------------------------------------------------------------------
 + Title        : StoreController 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2022/2/22 7:44
 + Last-time    : 2022/2/22 7:44+ chen2
 + Desc         : StoreController
 +----------------------------------------------------------------------
*/


namespace app\api\controller;

use app\common\model\Admin;
use app\common\model\AdminBusySd;
use app\common\model\AppointmentOrder;
use app\common\model\KqUserPlan;
use app\common\model\Service;
use app\common\model\ServicePackage;
use app\common\model\ServicePeriod;
use app\common\model\StoreLhsdCommissionConfig;
use app\common\model\StoreServicePeriod;
use app\common\model\StoreWorkingHoursConfig;
use app\common\service\ServicePackageService;
use app\common\service\ServiceService;
use app\common\service\StoreCardService;
use app\common\service\StoreService;
use app\common\service\StoreTypeService;
use app\common\service\WechatService;
use randy\MyQuery;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;


class StoreController extends ApiBaseController
{
    public function index() : Json
    {
        $data = $this->getParams();
        $data['is_delete'] = 0;
        $list = StoreService::getStoreList($data);
        return $this->returnSuccess($list);
    }

    public function getStoreItem($store_id) : Json
    {
        $data = $this->getParams();
        $service = new StoreService();
        $list = $service->getStoreItem($store_id, $data);
        return $this->returnSuccess($list);
    }

    /**
     * 获取门店banner
     *
     * @author : Randy_chen
     * @Date   : 2022/2/22
     * @Time   : 19:30
     */
    public function getStoreBanner($store_id) : Json
    {
        $list = StoreService::getStoreBanner($store_id);
        return $this->returnSuccess($list);
    }

    public function getStoreTypeList() : Json
    {
        $service = new StoreTypeService();
        $list = $service->getStoreTypeList([]);
        return $this->returnSuccess($list);
    }

    /**
     * 获取门店服务
     *
     * @author : Randy_chen
     * @Date   : 2022/2/22
     * @Time   : 19:34
     */
    public function getStoreService($store_id) : Json
    {
        $params = $this->getParams();
        $query = Service::build()
                        ->like('service_name')
                        ->with(['servicePeriod.storeServicePeriod'])
                        ->where('status', 1)
                        ->where('store_id', $store_id);
        if (!empty($params['service_period_id'])) {
            $query->whereIn('service_id', function (MyQuery $query) use ($params)
            {
                $query->name('service_period')
                      ->where('service_period_id', $params['service_period_id'])
                      ->field('service_id');
            });
        }


        $list = $query->select();

        // 获取门店工时价格
        $min_working_hours_price = StoreLhsdCommissionConfig::build()
                                                            ->where('store_id', $store_id)
                                                            ->min('price');
        $max_working_hours_price = StoreLhsdCommissionConfig::build()
                                                            ->where('store_id', $store_id)
                                                            ->max('price');

        foreach ($list as $item) {
            $durations = [];
            $item->servicePeriod->each(function ($servicePeriod) use ($item, &$durations)
            {
                if ($servicePeriod->storeServicePeriod) {
                    $durations[] = $servicePeriod->storeServicePeriod->duration;
                }
            });
            $item->duration = min($durations);
            $item->min_working_hours_price = $min_working_hours_price;
            $item->max_working_hours_price = $max_working_hours_price;
            $item->min_price = $min_working_hours_price * $item->duration;
            $item->max_price = $max_working_hours_price * $item->duration;
        }
        $list->hidden(['servicePeriod']);

        return $this->returnSuccess($list);
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function getTechnicianList($store_id, $service_period_id, $service_id) : Json
    {
        $search = $this->getParams();
        $list = Admin::build()
                     ->in('skill_level')
                     ->where('group_id', 'in', [2, 4])
                     ->where('store_id', $store_id)
                     ->select();
        $sc = StoreServicePeriod::build()
                                ->where('service_period_id', $service_period_id)
                                ->value('duration');

        $lhsd = StoreLhsdCommissionConfig::build()
                                         ->where('store_id', $store_id)
                                         ->column('price', 'sd_skill_level');
        $service_period = StoreServicePeriod::build()
                                            ->where('service_period_id', $search['service_period_id'])
                                            ->where('store_id', $search['store_id'])
                                            ->findOrFail();

        foreach ($list as $k => $v) {
            $v->is_can_service = 0;
            //查看当前技师当天是否正常上班
            $userPlan = KqUserPlan::build()
                                  ->where('kq_date', $search['appointment_date'])
                                  ->where('kq_type', 1)
                                  ->where('admin_id', $v->admin_id)
                                  ->find();
            if (!$userPlan) {
                unset($list[$k]);
                continue;
            }

            $v->sc = $service_period->duration;
            $price_result = ServiceService::getPrice($v->skill_level, 0, $search['store_id'], 1, $search['service_period_id'], $search['appointment_date'], $service_id);
            //计算金额
            $v->dj = $price_result['hdj'] ?: $price_result['dj'];
            $v->zj = $v->sc * $v->dj;
            if ($userPlan) {
                $v->is_can_service = 1;
                //时段强校验
                $flag = KqUserPlan::checkIsWork($userPlan, $service_period);
                if (!$flag) {
                    unset($list[$k]);
                    continue;
                }
                if (
                    AdminBusySd::build()
                               ->where('admin_id', $v->admin_id)
                               ->where('busy_date', $userPlan->kq_date)
                               ->where('service_period_id', $v->service_period_id)
                               ->find()
                ) {
                    $v->is_can_service = 0;
                }

                if (
                    AppointmentOrder::build()
                                    ->where('sd_admin_id', $v->admin_id)
                                    ->where('appointment_date', $userPlan->kq_date)
                                    ->where('service_period_id', $v->service_period_id)
                                    ->find()
                ) {
                    $v->is_can_service = 0;
                }
            }

            $v->min_price = $sc * $lhsd[$v->skill_level];
        }
        return $this->returnSuccess(array_values($list->toArray()));
    }

    /**
     * 获取联合上单技师列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author : Randy_chen
     * @Date   : 2022/6/1
     * @Time   : 7:04
     */
    public function getLHTechnicianList($service_id) : Json
    {
        $search = $this->getParams();
        $admin = Admin::build()
                      ->findOrFail($search['admin_id']);
        $service_period = StoreServicePeriod::build()
                                            ->where('service_period_id', $search['service_period_id'])
                                            ->where('store_id', $search['store_id'])
                                            ->findOrFail();
        // 获取自己的上级和下级
        $sf = Admin::build()
                   ->where('admin_id', $admin->teacher)
                   ->where('group_id', 'in', [2, 4])
                   ->select();
        foreach ($sf as $k => $item) {
            $item->is_can_service = 0;
            $item->sc = $service_period->duration;
            $price_result = ServiceService::getPrice($admin->skill_level, $item->skill_level, $search['store_id'], 1, $search['service_period_id'], $search['appointment_date'], $service_id);
            if (!$price_result) {
                unset($sf[$k]);
                continue;
            }
            //计算金额
            $item->dj = $price_result['hdj'] ?: $price_result['dj'];
            $item->zj = $item->sc * $item->dj;
            $item->activity = $price_result['activity'];
            //查看当前技师当天是否正常上班
            $userPlan = KqUserPlan::build()
                                  ->where('kq_date', $search['appointment_date'])
                                  ->where('kq_type', 1)
                                  ->where('admin_id', $item->admin_id)
                                  ->find();
            if (!$userPlan) {
                unset($sf[$k]);
                continue;
            }
            if (!KqUserPlan::checkIsWork($userPlan, $service_period)) {
                unset($sf[$k]);
                continue;
            }

            if ($userPlan) {
                $item->is_can_service = 1;
                if (
                    AdminBusySd::build()
                               ->where('admin_id', $item->admin_id)
                               ->where('busy_date', $userPlan->kq_date)
                               ->where('service_period_id', $item->service_period_id)
                               ->find()
                ) {
                    $item->is_can_service = 0;
                }
            }
        }

        $td = Admin::build()
                   ->where('group_id', 'in', [2, 4])
                   ->where('teacher', $admin->admin_id)
                   ->select();
        foreach ($td as $kk => $item) {
            $item->is_can_service = 0;
            $item->sc = $service_period->duration;
            $price_result = ServiceService::getPrice($item->skill_level, $admin->skill_level, $search['store_id'], 1, $search['service_period_id'], $search['appointment_date'], $service_id);
            if (!$price_result) {
                unset($td[$k]);
                continue;
            }
            //计算金额
            $item->dj = $price_result['hdj'] ?: $price_result['dj'];
            $item->zj = $item->sc * $item->dj;
            $item->activity = $price_result['activity'];
            //查看当前技师当天是否正常上班
            $userPlan = KqUserPlan::build()
                                  ->where('kq_date', $search['appointment_date'])
                                  ->where('kq_type', 1)
                                  ->where('admin_id', $item->admin_id)
                                  ->find();
            if (!$userPlan) {
                unset($td[$k]);
                continue;
            }
            if (!KqUserPlan::checkIsWork($userPlan, $service_period)) {
                unset($td[$kk]);
                continue;
            }

            if ($userPlan) {
                $item->is_can_service = 1;
                if (
                    AdminBusySd::build()
                               ->where('admin_id', $item->admin_id)
                               ->where('busy_date', $userPlan->kq_date)
                               ->where('service_period_id', $item->service_period_id)
                               ->find()
                ) {
                    $item->is_can_service = 0;
                }
            }
        }
        return $this->returnSuccess(compact('sf', 'td'));
    }

    /**
     * 获取门店健康包
     *
     * @param $store_id
     *
     * @return Json
     * @author : Randy_chen
     * @Date   : 2022/2/23
     * @Time   : 22:20
     */
    public function getStoreServicePackageList($store_id)
    {
        $list = ServicePackageService::getStoreServiceList($store_id);
        return $this->returnSuccess($list);
    }

    public function getStoreServicePackageItem($id)
    {
        $item = ServicePackageService::getServicePackageItem($id);

        return $this->returnSuccess($item);
    }

    //获取门店里程卡
    public function getStoreServiceCardList() : Json
    {
        $list = StoreCardService::getstoreCardList();//->hidden(['store_card_service', 'create_time', 'update_time']);

        return $this->returnSuccess($list);
    }

    //获取门店里程卡
    public function getStoreServiceCardItem() : Json
    {
        $data = $this->getParams();
        $item = StoreCardService::getstoreCardItem(1);
        $item->service_num = count($item->store_card_service);
        return $this->returnSuccess($item);
    }


    public function pay()
    {
        $options = [
            'body'             => '订单支付',
            'out_trade_no'     => rand(1000000000, 9999999999),
            'total_fee'        => 1,
            'spbill_create_ip' => '127.0.0.1',
            'auth_code'        => '134715043276517526',
        ];
        //        try {
        $pay = WechatService::WePayOrder();
        $info = $pay->micropay($options);
        dd($info);
        //            if ($info['return_code'] === 'SUCCESS' && $info['result_code'] === 'SUCCESS') {
        //                return $this->returnSuccess($pay->jsapiParams($info['prepay_id']));
        //            }
        //            if (isset($info['err_code_des'])) throw new \think\Exception($info['err_code_des']);
        //        } catch (\Exception $e) {
        //            throw new ApiException(1, "创建订单失败参数失败，{$e->getMessage()}");
        //        }
    }
}